package com.wt.admin.config.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.exp.impl.BasicException;
import com.aizuda.easy.security.handler.RepFunctionHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class JsonExceptionHandler implements RepFunctionHandler {
    @Override
    public String exec(HttpServletResponse response, String json) throws BasicException, IOException {
        // 解决两个code 问题
        if (StrUtil.isBlank(json)) {
            return json;
        }
        String regex = "\\{[\\s\\S]*?\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(json);
        List<String> jsonStrings = new ArrayList<>();
        while (matcher.find()) {
            jsonStrings.add(matcher.group());
        }
        for (String jsonString : jsonStrings) {
            try {
                Rep<?> rep = JSONUtil.toBean(jsonString, Rep.class);
                if (rep.getCode().intValue() != 200) {
                    json = jsonString;
                }
            }catch (Exception e){

            }
        }
        return json;
    }

    @Override
    public Integer getIndex() {
        return 20;
    }
}
